﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;
using System.Reflection;
using System.IO;

/**
 *
 * @author eladh, alaah
 */

namespace Windows_System_Snapshot
{
    public partial class Form1 : Form
    {
        private Logic logical;
        private string HTMLpath;

        private Thread messageUpdaterThread;
        private String proccessedCommand;
        private bool isDone = false;
        private string lspciDir = "";
        // Constructor 
        //
        //-------------------------------------------------------------------------------------------
        //
        public Form1()
        {
            logical = null;
            InitializeComponent();
            pathTextBox.Text = HTMLpath = Logic.DEFAULT_OUTPUT_PATH;
            hideWaitPanel();

            // add tool tip to the company logo
            ToolTip logoToolTip = new ToolTip();
            logoToolTip.SetToolTip(logoPictureBox, "Click here to navigate to www.mellanox.com");

            this.Text += " - " + ProductVersion;
            
            logical = new Logic();
            logical.startScaningCards();
            logical = null;
            
            //
            // extract the embedded pciutils file to a temp folder
        	//
            lspciDir = System.IO.Path.GetTempPath() + "mx" + System.IO.Path.GetRandomFileName();
            Directory.CreateDirectory(lspciDir);
        	EmbeddedResource.RecreateEmbeddedResource("zlib1.dll", lspciDir);
        	EmbeddedResource.RecreateEmbeddedResource("DirectIOLib32.dll", lspciDir);
        	EmbeddedResource.RecreateEmbeddedResource("lspci.exe", lspciDir);
        	EmbeddedResource.RecreateEmbeddedResource("pci.ids.gz", lspciDir);
			// set the path to lspci.exe
			LogicAbstract.lspciPath = lspciDir + @"\lspci.exe";
            
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// Generate HTML button handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void genHTMLBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (HTMLpath.Equals(""))
                {
                    MessageBox.Show("Please, choose the target file for saving the information", "Target file not chosen", MessageBoxButtons.OK);
                }
                else
                {
                    if (genHTMLBtn.Text.Equals("Generate HTML"))
                    {
                        logical = new Logic();
                        logical.startNewThread(HTMLpath);
                        choosePAthBtn.Enabled = false;
                        genHTMLBtn.Text = "Stop";

                        // start the proccessed Command message updater thread
                        ThreadStart ths = new ThreadStart(this.proccessedCommandUpdater);
                        messageUpdaterThread = new Thread(ths);
                        messageUpdaterThread.Start();

                        showWaitPanel();
            			
                    }
                    else // stop
                    {
                        stop();
                        MessageBox.Show("Gathering the information has been stopped.", "Proccess stopped", MessageBoxButtons.OK);
                    }
                }
            }
            catch
            {
                MessageBox.Show("Error terminating process", "Proccess interrupted", MessageBoxButtons.OK);
            }
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// stops the threads, and reset the button's text
        /// </summary>
        private void stop()
        {
            logical.stopThread();
            logical = null;
            choosePAthBtn.Enabled = true;
            genHTMLBtn.Text = "Generate HTML";
            hideWaitPanel();
            messageUpdaterThread.Abort();
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// displays the "wait message" and the progressbar.
        /// </summary>
        public void showWaitPanel()
        {
            pleaseWaitMsgLabel1.Visible = true;
            progressBar1.Style = ProgressBarStyle.Marquee;
            progressBar1.Visible = true;
            nowProccessed.Visible = true;
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// hides the "wait message" and the progressbar.
        /// </summary>
        private void hideWaitPanel()
        {
            progressBar1.Visible = false;
            pleaseWaitMsgLabel1.Visible = false;
            nowProccessed.Visible = false;
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// "set target file" button handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void choosePAthBtn_Click(object sender, EventArgs e)
        {
            SaveFileDialog fd = new SaveFileDialog();
            fd.Filter = "HTML files|*.html|All Files|*.*";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                if (fd.FileName != "")
                {
                    try
                    {
                        // display the file name in the text box
                        pathTextBox.Text = fd.FileName;

                        // set the path
                        HTMLpath = fd.FileName;
                    }
                    catch
                    {
                        MessageBox.Show("Error creating output file!", "Proccess interrupted", MessageBoxButtons.OK);
                    }
                }
            }
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// handler for the exit button from the navigation menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// handler for the version button from the navigation menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void versionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Mellanox Technologies\nMellanox Windows System Information Snapshot Utility\nVersion: " + new AssemblyName(System.Reflection.Assembly.GetExecutingAssembly().FullName).Version.ToString(), "Windows System Snapshot", MessageBoxButtons.OK);
            (new AboutBox1()).ShowDialog();
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// handler for clicking on the Mellanox logo.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(new ProcessStartInfo("http://www.mellanox.com/"));
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// displays the current running command 
        /// </summary>
        private void proccessedCommandUpdater()
        {
            while (true)
            {
                proccessedCommand = logical.getProccessedCommand();
                isDone = logical.isDone;
                accessControl();
            }
        }
        // accesses a vaiable of another thread.
        private void accessControl()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(accessControl));
            }
            else
            {
                nowProccessed.Text = "Processing: " + proccessedCommand;
                if (isDone)
                {
                    // stop the threads
                    stop();
                    // display Done message.
                    nowProccessed.Text = "Done";
                    nowProccessed.Visible = true;
                    //
                    MessageBox.Show("The system snapshot file \"" + HTMLpath + "\" was created successfully!", "File Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    selectFileInfolder(HTMLpath);
                }
            }
        }
        /// <summary>
        /// open a folder and selects the file.
        /// </summary>
        /// <param name="filePath"></param>
        private void selectFileInfolder(string filePath)
        {
            try
            {
                string windir = Environment.GetEnvironmentVariable("windir");
                if (string.IsNullOrEmpty(windir.Trim()))
                {
                    windir = "C:\\Windows\\";
                }
                if (!windir.EndsWith("\\"))
                {
                    windir += "\\";
                }

                FileInfo fileToLocate = null;
                fileToLocate = new FileInfo(filePath);

                ProcessStartInfo pi = new ProcessStartInfo(windir + "explorer.exe");
                pi.Arguments = "/select, \"" + fileToLocate.FullName + "\"";
                pi.WindowStyle = ProcessWindowStyle.Normal;
                pi.WorkingDirectory = windir;

                //Start Process
                Process.Start(pi);
            }
            catch { }
        }
        //
        //-------------------------------------------------------------------------------------------
        //
        /// <summary>
        /// handle for closing the window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
        	EmbeddedResource.DeleteFolderRec(lspciDir);
            System.Environment.Exit(0);
        }
        //
        //------------------------------------------------f-------------------------------------------
        //
        /// <summary>f
        /// handler for the options button from the navigation menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
        	(new Settings()).ShowDialog();
        	
//            // InputBox with value validation - first define validation delegate, which
//            // returns empty string for valid values and error message for invalid values
//            InputBoxValidation validation = delegate(string val)
//            {
//                if (val == "")
//                    return "Value cannot be empty.";
//                if (!(new Regex(@"^[0-9]{1,}$")).IsMatch(val))
//                {
//                    return "Please enter only an integer number.";
//                }
//                if (Int32.Parse(val) < 1)
//                {
//                    return "The Timeout must be greater than 0.";
//                }
//                return "";
//            };
//
//            string value = timeOut.ToString();
//            if (InputBox.Show("Options", "Timeout (seconds):", ref value, validation) == DialogResult.OK)
//            {
//                f = Int32.Parse(value);
//            }
        }
        //
        //-------------------------------------------------------------------------------------------
        //
    }
}
